﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Algoritmia.DataStructures.Sets
{
    public class CollectionSet<T> : ISet<T>
    {
        private readonly Collections.ICollection<T> _collection;

        public CollectionSet(IEnumerable<T> data=null, 
            Func<Collections.ICollection<T>> createCollection=null)
        {
            data = data ?? Enumerable.Empty<T>();
            createCollection = createCollection ?? (() => new Collections.LinkedListCollection<T>());
            _collection = createCollection();
            foreach (var item in data)
            {
                Add(item);
            }

        }

        #region ISet<T> members

        public bool Contains(T elem)
        {
            return _collection.Contains(elem);
        }

        public void Add(T elem)
        {
            if (!Contains(elem))
                _collection.Add(elem);
        }

        public virtual void AddUnchecked(T elem)
        {
            _collection.Add(elem);
        }

        public virtual void Discard(T elem)
        {
            _collection.Remove(elem);
        }

        public virtual bool Remove(T elem)
        {
            return _collection.Remove(elem);
        }

        public virtual void Clear()
        {
            _collection.Clear();
        }

        #endregion

        #region IEnumerable<T> members

        public virtual IEnumerator<T> GetEnumerator()
        {
           return _collection.GetEnumerator();
        }

        #endregion

        #region ICountable Members

        public virtual int Count
        {
            get { return _collection.Count; }
        }
        #endregion

        #region IEnumerable members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _collection.GetEnumerator();
        }

        #endregion

        #region IEquatable<ISet<T>> members

        public virtual bool Equals(ISet<T> other)
        {
            return Count == other.Count && this.IsSuperSetOf(other);
        }

        #endregion

        public override string ToString()
        {
            return String.Format("{0} <{1}> {{{2}}}", GetType().Name, typeof(T).Name, string.Join(",",this));
        }
    }
}
